package org.openclinic.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.openclinic.domain.HealthProfessional;
import org.openclinic.exception.DomainException;
import org.openclinic.exception.ErrorCodes;
import org.openclinic.repository.HealthProfessionalRepository;
import org.openclinic.service.HealthProfessionalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;

@Service
public class HealthProfessionalServiceImpl implements HealthProfessionalService {
	
	@Autowired
	private HealthProfessionalRepository healthProfessionalRepository;
	
	@Override
	public void delete(long id) {
		try {
			healthProfessionalRepository.delete(id);
		} catch (DataIntegrityViolationException e) {
			throw new DomainException("healthProfessional", "name", ErrorCodes.FOREIGN_KEY_VIOLATED, String.valueOf(id));
		}
	}
	
	@Override
	public HealthProfessional find(long id) {
		return healthProfessionalRepository.findOne(id);
	}
	
	@Override
	public List<HealthProfessional> findBySpecialty(long specialtyId) {
		return healthProfessionalRepository.findBySpecialty(specialtyId);
	}
	
	@Override
	public List<HealthProfessional> list() {
		return healthProfessionalRepository.findAllHealthProfessionals();
	}
	
	@Override
	public HealthProfessional save(HealthProfessional healthProfessional) {
		Date currentDate = new Date();
		
		if (healthProfessional.getUserId() == null) {
			String password = UUID.randomUUID().toString().toUpperCase().substring(28).replace('A', 'S').replace('E', 'J');
			
			healthProfessional.setActive(true);
			healthProfessional.setPassword(password);
			healthProfessional.setCreationDate(currentDate);
		}
		
		healthProfessional.setLastUpdate(currentDate);
		return healthProfessionalRepository.save(healthProfessional);
	}
}
